<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-24 10:22:36
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\contranctTask.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="单位名称" label-width="80px">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系人">
            <el-input
              v-model="queryParams.contactsName"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="tableoperation">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        v-hasPermi="['task:tasksContract:add']"
        @click.native.prevent="openDialog()"
        >添加</el-button
      >
    </div>

    <el-tabs v-model="activeName" @tab-click="changeTab" class="tab">
      <el-tab-pane label="待发起" name="0" v-if="isPer"></el-tab-pane>
      <el-tab-pane label="待审批" name="1"></el-tab-pane>
      <!-- <el-tab-pane label="已通过" name="2"></el-tab-pane> -->
      <el-tab-pane label="已签发" name="2"></el-tab-pane>
      <el-tab-pane label="已退回" name="3"></el-tab-pane>
    </el-tabs>
    <el-table
      v-loading="loading"
      :data="contractList"
      :height="height - 450 + 'px'"
      @row-dblclick="(row) => openDialog(row, '3')"
    >
      <el-table-column
        label="单位名称"
        align="center"
        prop="organizationName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="联系人"
        align="center"
        prop="contactsName"
        width="150"
      />
      <el-table-column
        label="联系电话"
        align="center"
        prop="contactsMobile"
        width="150"
      />
      <el-table-column
        label="单位地址"
        align="center"
        prop="organizationAddress"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <dict-tag :options="dict.type.tasks_tate" :value="row.tasksState" />
        </template>
      </el-table-column>
      <el-table-column label="评审记录" align="center">
        <template slot-scope="{ row }">
          <el-link
            type="primary"
            @click="handlePrintContractReviewTable(row)"
            v-if="row.reviewOssId"
            >查看</el-link
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.tasksState == '0'"
            v-hasPermi="['task:tasksContract:apply']"
            @click.native.prevent="handleContractApply(row)"
            type="text"
          >
            发起
          </el-button>
          <el-button
            v-if="row.canAudit == '1'"
            v-hasPermi="['task:tasksContract:process']"
            @click.native.prevent="openDialog(row, '4')"
            type="text"
          >
            审核
          </el-button>
          <el-button
            v-hasPermi="['task:tasksContract:edit']"
            v-if="
              row.tasksState == '0' ||
              row.tasksState == '1' ||
              row.tasksState == '3'
            "
            @click.native.prevent="openDialog(row, '2')"
            type="text"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['task:tasksContract:remove']"
            v-if="row.tasksState == '0' || row.tasksState == '3'"
            @click.native.prevent="handleDelete(row)"
            type="text"
            style="color: #f32d2d"
          >
            删除
          </el-button>
          <el-button
            v-if="
              row.tasksState == '1' ||
              row.tasksState == '2' ||
              row.tasksState == '3'
            "
            @click.native.prevent="handleFlowRecord(row)"
            type="text"
          >
            查看流程
          </el-button>
          <el-button
            type="text"
            @click="handleOpenContractReviewRecordTable(row)"
            >合同评审</el-button
          >
          <el-button
            type="text"
            @click="handleGenerateContract(row)"
            v-if="activeName == '2'"
            >生成合同</el-button
          >
          <el-button
            type="text"
            @click="handleGenerateTask(row)"
            v-if="activeName == '2'"
            >生成任务</el-button
          >
          <!-- <el-button
            type="text"
            @click="handleGenerateContractReviewTable(row)"
          >生成</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1100px"
      class="adddialog"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3' || status == '4' || !isPer"
        :rules="rules"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位名称" prop="entrustOrganizationId">
              <m-select
                v-if="!(status == '3' || status == '4' || !isPer)"
                v-model="form.entrustOrganizationId"
                :dimStr="form.organizationName"
                :placeholder="status != '3' ? '输入文字检索查询' : ''"
                style="width: 95%"
                filterable
                :disabled="!isPer"
                @change="changeEntrustOrganization"
                clearable
                :lists="entrustOrganizationSelect"
                lists_label="organizationName"
                lists_value="entrustOrganizationId"
                lists_key="entrustOrganizationId"
                :total="orgTotal"
                :pageSize="10"
                @handleChange="listeningEvent"
              >
              </m-select>
              <el-input v-else v-model="form.organizationName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contactsName">
              <el-input v-model="form.contactsName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactsMobile">
              <el-input v-model="form.contactsMobile" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位地址">
              <el-input v-model="form.organizationAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="要求完成日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.requireCompletionDate"
                value-format="yyyy-MM-dd"
                type="date"
                :placeholder="status != '3' ? '请选择' : ''"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核">
              <el-select
                v-model="form.launchState"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in dict.type.is_or_no"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="innertitle">
        <span>检测清单</span>
        <el-button
          class="addline"
          type="primary"
          size="mini"
          @click.native.prevent="addline()"
          v-if="status != '3' && status != '4' && isPer"
          >添行</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="form.tasksContractItemList"
        height="350"
      >
        <el-table-column
          label="设备类型"
          type="index"
          prop="entrustEquipmentTypeId"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.entrustEquipmentTypeId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              size="mini"
              :disabled="status == '3' || status == '4' || !isPer"
              filterable
              :ref="'equipmentType_' + scope.$index"
              @change="changeEquipmentType($event, scope.$index)"
              clearable
            >
              <el-option
                v-for="item in entrustEquipmentTypeSelect"
                :label="item.name"
                :value="item.entrustEquipmentTypeId"
                :key="item.entrustEquipmentTypeId"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="台件数" align="center" prop="num" width="100">
          <template slot-scope="scope">
            <el-input
              :ref="'slidesRef_' + scope.$index"
              v-model="scope.row.num"
              size="mini"
              :disabled="status == '3' || status == '4' || !isPer"
              @change="changeNum($event, scope.$index)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="检测类型"
          align="center"
          prop="inspectionTypeId"
        >
          <template slot-scope="scope">
            <div class="inspect" v-if="scope.row.entrustEquipmentTypeName">
              <template v-if="scope.row.largeCategory == '2'">
                <el-checkbox-group
                  :disabled="status == '3' || status == '4' || !isPer"
                  class="inspectcheckbox"
                  v-model="scope.row.CG"
                >
                  <el-checkbox
                    v-for="(item, index) in CGInspectList"
                    :key="index"
                    :label="item.inspectionTypeId"
                    >{{ item.typeName }}</el-checkbox
                  >
                </el-checkbox-group>
              </template>
              <template v-else-if="scope.row.largeCategory == '3'">
                <el-checkbox
                  v-model="scope.row.radioInspecId"
                  disabled
                  checked
                  :true-label="FHInspectList[0].inspectionTypeId"
                  :label="FHInspectList[0].inspectionTypeId"
                  >防护检测</el-checkbox
                >
              </template>
              <template v-else>
                <el-checkbox-group
                  :disabled="status == '3' || status == '4' || !isPer"
                  class="inspectcheckbox"
                  v-model="scope.row.FH"
                >
                  <el-checkbox
                    v-for="(item, index) in FHInspectList"
                    :key="index"
                    :label="item.inspectionTypeId"
                    >{{ item.typeName }}</el-checkbox
                  >
                </el-checkbox-group>
                <el-radio-group
                  :disabled="status == '3' || status == '4' || !isPer"
                  class="inspectradio"
                  v-model="scope.row.radioInspecId"
                >
                  <el-radio
                    v-for="(item, index) in radioInspectList"
                    :key="index"
                    :label="item.inspectionTypeId"
                    @click.native.prevent="
                      handleChangeRadioInspecId(
                        scope.row,
                        scope.$index,
                        item.inspectionTypeId
                      )
                    "
                    >{{ item.typeName }}</el-radio
                  >
                </el-radio-group>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="amounit" width="100">
          <template slot-scope="scope">
            <el-input
              :ref="'slidesRef_' + scope.$index"
              v-model="scope.row.amount"
              size="mini"
              :disabled="status == '3' || status == '4' || !isPer"
              @change="changeAmount($event, scope.$index)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="total" width="100">
          <template slot-scope="scope">
            <el-input
              :ref="'slidesRef_' + scope.$index"
              v-model="scope.row.total"
              size="mini"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          v-if="status != '3' && status != '4' && isPer"
          align="center"
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteData(scope.$index)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span style="line-height: 50px">合计：{{ totalprice }}</span>
      <!-- <div style="float: right; margin-top: 5px">
        <el-button type="primary" :disabled="status == '3'" @click="handleOpenContractReviewTable">合同评审表</el-button>
        <el-button type="primary" :disabled="status == '3'" @click="handleOpenContractReviewRecordTable">合同评审记录表</el-button>
        <el-button type="primary" :loading="generateBtnLoading" @click="handleGenerateContractReviewTable">生成</el-button>
        <el-button type="primary" @click="handlePrintContractReviewTable" v-if="reviewOssId">打印</el-button>
      </div> -->

      <div slot="footer">
        <el-button
          type="primary"
          v-if="status == '1' || status == '2'"
          @click="submitForm"
          >确 定</el-button
        >
        <el-button
          type="success"
          v-if="status == '4'"
          @click="handleProcess('2')"
          >通 过</el-button
        >
        <el-button
          type="danger"
          v-if="status == '4'"
          @click="handleProcess('3')"
          style="margin-right: 50px"
          >驳 回</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 意见弹框 -->
    <el-dialog
      title="审批意见"
      :visible.sync="manageVisible"
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag="true"
    >
      <el-input
        v-model="manageForm.comment"
        type="textarea"
        placeholder="请输入审批意见"
        clearable
      />
      <div slot="footer">
        <el-button type="primary" @click="submitManageData">确 定</el-button>
      </div>
    </el-dialog>
    <WorkFlow ref="workFlow"></WorkFlow>

    <ContractReviewTableDialog
      :show.sync="showContractReviewTableDialog"
      :row="currRow"
      :data="contractReviewTableData"
      @temp-save="handleContractReviewTableTempSave"
    ></ContractReviewTableDialog>

    <ContractReviewRecordTableDialog
      :show.sync="showContractReviewRecordTableDialog"
      :row="currRow"
      :data="contractReviewRecordTableData"
      :entry="1"
      :totalPrice="totalprice"
      @temp-save="handleContractReviewRecordTableTempSave"
      @refresh="getList"
    ></ContractReviewRecordTableDialog>
  </div>
</template>

<script>
import {
  contractProcess,
  contractEdit,
  contractApply,
  contractAdd,
  tasksContractBindList,
  contractRemove,
  contractList,
  contractDetail,
  getInspectionList,
  generateContractReviewContent,
  generateContract,
  generateDetectionTogetherTask,
} from "@/api/slides/contractTask";
import { listByIds } from "@/api/system/oss";
import {
  entrustOrganizationListing,
  entrustOrganizationDetail,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { entrustEquipmentTypeListing } from "@/api/person/entrustEquipmentType";
import WorkFlow from "@/components/WorkFlow";
import MSelect from "@/components/mSelect";
import ContractReviewTableDialog from "./component/ContractReviewTableDialog";
import ContractReviewRecordTableDialog from "./component/ContractReviewRecordTableDialog";
import {
  saveContractReviewContent,
  saveContractReviewRecordContent,
} from "@/api/slides/contractTask";

export default {
  name: "contranctTask",
  dicts: ["tasks_tate", "is_or_no"],
  components: {
    WorkFlow,
    MSelect,
    ContractReviewTableDialog,
    ContractReviewRecordTableDialog,
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        state: "0",
      },
      total: 0,
      dialogVisible: false,
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      rules: {
        entrustOrganizationId: [
          { required: true, message: "单位名称不能为空", trigger: "change" },
        ],
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 合同列表
      contractList: [],
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      // 设备类型下拉框
      entrustEquipmentTypeSelect: [],
      // 检测类型下拉框
      inspectionList: [],
      CGInspectList: [],
      FHInspectList: [],
      radioInspectList: [],
      // 合计
      totalprice: 0,
      activeName: "0",
      isPer: false,
      isHide: false,
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      manageVisible: false,
      manageForm: {},

      showContractReviewTableDialog: false,
      contractReviewTableIsTempSave: false,
      contractReviewTableData: {},
      showContractReviewRecordTableDialog: false,
      contractReviewRecordTableIsTempSave: false,
      contractReviewRecordTableData: {},
      currRow: {},
      generateBtnLoading: false,
      reviewOssId: "",
    };
  },
  created() {
    // 未发起栏的权限控制（领导层没有）
    let permissions = this.$store.getters.permissions;
    let found = permissions.find((item) => {
      return item == "task:tasksContract:apply";
    });
    this.isPer = found == "task:tasksContract:apply" || permissions == "*:*:*";
    if (this.isPer) {
      this.getInspectionListing();
    } else {
      /* 领导层 */
      this.activeName = "1";
      this.queryParams.state = "1";
    }
    this.getList();
    this.getEntrustEquipmentTypeListing();
  },
  methods: {
    // 切换tab栏
    changeTab(tab, event) {
      this.queryParams.state = tab.name;
      this.contractList = [];
      this.getList();
    },
    // 获取合同任务列表
    getList() {
      this.loading = true;
      contractList(this.queryParams)
        .then((response) => {
          this.contractList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取设备类型下拉框
    getEntrustEquipmentTypeListing() {
      entrustEquipmentTypeListing().then((response) => {
        this.entrustEquipmentTypeSelect = response.data;
      });
    },
    // 获取检测类型下拉框
    getInspectionListing() {
      getInspectionList().then((response) => {
        this.inspectionList = response.rows;
        this.CGInspectList = this.inspectionList.filter((item) => {
          return item.typeName == "常规监测";
        });
        this.FHInspectList = this.inspectionList.filter((item) => {
          return item.typeName == "防护检测";
        });
        this.radioInspectList = this.inspectionList.filter((item) => {
          return item.typeName != "常规监测" && item.typeName != "防护检测";
        });
      });
    },
    // 打开对话框
    openDialog(row, status) {
      this.currRow = row;
      this.resetForm("form");
      this.form = {};
      if (row) {
        contractDetail(row.tasksContractId).then((response) => {
          let responsedata = response.data;
          this.reviewOssId = responsedata.reviewOssId;
          if (
            responsedata.tasksContractItemList &&
            responsedata.tasksContractItemList.length != 0
          ) {
            responsedata.tasksContractItemList.forEach((item) => {
              item.amount /= 100;
              item.total = item.num * item.amount;
              item.CG = [];
              item.FH = [];
              item.radioInspecId = null;
              item.largeCategory =
                this.entrustEquipmentTypeSelect.find(
                  (ite) =>
                    ite.entrustEquipmentTypeId == item.entrustEquipmentTypeId
                )?.largeCategory || null;
              let arr = item.inspectionTypeId.split(",");
              arr.forEach((itemid) => {
                let findObj = this.inspectionList.find((inspectionitem) => {
                  return inspectionitem.inspectionTypeId == itemid;
                });
                if (findObj) {
                  console.log("111");
                  if (findObj.typeName == "常规监测") {
                    item.CG = [findObj.inspectionTypeId];
                  } else if (findObj.typeName == "防护检测") {
                    item.FH = [findObj.inspectionTypeId];
                  } else {
                    item.radioInspecId = findObj.inspectionTypeId;
                  }
                }
              });
            });
          }
          this.form = responsedata;
          this.calculateTotalprice();
          this.dialogVisible = true;
        });
        if (status == "2") {
          this.status = "2";
          this.title = "编辑合同任务";
        }
        if (status == "3") {
          this.status = "3";
          this.title = "查看合同任务";
        }
        if (status == "4") {
          this.status = "4";
          this.title = "审核合同任务";
        }
      } else {
        this.form = {
          contactsName: null,
          organizationAddress: null,
          contactsMobile: null,
          tasksContractItemList: [
            {
              CG: [],
              FH: [],
              radioInspecId: null,
              total: null,
            },
          ],
          launchState: "0",
        };
        this.autoSelectDose();
        this.totalprice = 0;
        this.status = "1";
        this.title = "添加合同任务";
        this.dialogVisible = true;
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        let copyForm = JSON.parse(JSON.stringify(this.form));
        if (copyForm.tasksContractItemList.length == 0) {
          this.$modal.msgWarning("请添加设备");
          return;
        }
        let isEmpty = copyForm.tasksContractItemList.some((item) => {
          if (!item.entrustEquipmentTypeId) {
            this.$modal.msgWarning("设备类型不能为空");
            return true;
          }
          if (!item.num) {
            this.$modal.msgWarning("台件数不能为空");
            return true;
          }
          if (
            item.CG.length == 0 &&
            item.FH.length == 0 &&
            !item.radioInspecId
          ) {
            this.$modal.msgWarning("检测类型不能为空");
            return true;
          }
          // if (!item.amount) {
          // 	this.$modal.msgWarning("单价不能为空");
          // 	return true;
          // }
        });
        if (isEmpty) {
          /* 有空值 */
          return;
        } else {
          /* 都有值 */
          copyForm.tasksContractItemList.forEach((item) => {
            let arr = [];
            if (item.CG.length != 0) {
              arr.push(...item.CG);
            }
            if (item.FH.length != 0) {
              arr.push(...item.FH);
            }
            if (item.radioInspecId) {
              arr.push(item.radioInspecId);
            }
            item.inspectionTypeId = arr.join(",");
            delete item.CG;
            delete item.FH;
            delete item.radioInspecId;
            item.amount *= 100;
            delete item.total;
          });
        }
        if (this.status == "1") {
          contractAdd(copyForm).then(async (response) => {
            this.$modal.msgSuccess("新增成功");
            if (this.contractReviewTableIsTempSave) {
              const data1 = JSON.parse(
                JSON.stringify(this.contractReviewTableData)
              );
              data1.tasksContractId = response.data;
              data1.category = data1.category.join(",");
              await saveContractReviewContent(data1);
            }
            if (this.contractReviewRecordTableIsTempSave) {
              const data2 = JSON.parse(
                JSON.stringify(this.contractReviewRecordTableData)
              );
              data2.tasksContractId = response.data;
              data2.conclusion = data2.conclusion.join(",");
              saveContractReviewRecordContent(data2);
            }
            this.dialogVisible = false;
            this.contractReviewTableIsTempSave = false;
            this.contractReviewTableData = {};
            this.contractReviewRecordTableIsTempSave = false;
            this.contractReviewRecordTableData = {};
            this.getList();
          });
        } else if (this.status == "2") {
          contractEdit(copyForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    submitManageData() {
      contractProcess(this.manageForm).then((response) => {
        this.dialogVisible = false;
        this.manageVisible = false;
        this.manageForm = {};
        this.getList();
        this.$modal.msgSuccess("操作成功");
      });
    },
    // 通过/驳回
    handleProcess(tasksState) {
      console.log(tasksState);
      this.manageForm = {
        tasksContractId: this.form.tasksContractId,
        tasksState: tasksState,
      };
      this.manageVisible = true;
      // contractProcess(
      // 	{
      // 		tasksContractId: this.form.tasksContractId,
      // 		tasksState: tasksState
      // 	}
      // ).then((response) => {
      //   this.$modal.msgSuccess("操作成功");
      // 	this.dialogVisible = false;
      //   this.getList();
      // });
    },
    // 发起
    handleContractApply(row) {
      this.$modal
        .confirm(`是否确认发起该合同任务？`)
        .then(() => {
          this.loading = true;
          return contractApply({
            id: row.tasksContractId,
          });
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 查看流程
    handleFlowRecord(row) {
      this.$refs.workFlow.openDialog(row);
    },
    // 删除外层列表
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除该合同任务？`)
        .then(() => {
          this.loading = true;
          return contractRemove(row.tasksContractId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 删除弹框里列表
    deleteData(index) {
      this.$modal.confirm(`是否确认删除该数据？`).then(() => {
        this.form.tasksContractItemList.splice(index, 1);
      });
    },
    // 更改委托单位下拉
    changeEntrustOrganization(val) {
      entrustOrganizationDetail(val).then((response) => {
        this.form.contactsName = response.data.contactsName;
        this.form.organizationAddress = response.data.addressDetails;
        this.form.contactsMobile = response.data.contactsMobile;
      });
    },
    // 更改设备类型下拉
    changeEquipmentType(val, index) {
      console.log(val);
      let selectEquipment =
        this.entrustEquipmentTypeSelect.find(
          (item) => item.entrustEquipmentTypeId == val
        ) || {};
      this.$nextTick(() => {
        this.$set(
          this.form.tasksContractItemList[index],
          "entrustEquipmentTypeName",
          this.$refs[`equipmentType_${index}`].selectedLabel
        );
        this.$set(
          this.form.tasksContractItemList[index],
          "largeCategory",
          selectEquipment.largeCategory
        );
      });
      // 重置值
      this.form.tasksContractItemList[index].CG = [];
      this.form.tasksContractItemList[index].FH = [];
      this.form.tasksContractItemList[index].radioInspecId = null;
    },
    // 查询重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        state: this.isPer ? "0" : "1",
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 添行
    addline() {
      this.form.tasksContractItemList.push({
        CG: [],
        FH: [],
        radioInspecId: null,
        total: null,
      });
      this.autoSelectDose();
    },
    // 自动选择个人剂量
    autoSelectDose() {
      const maxIndex = this.form.tasksContractItemList.length;
      const entrustEquipmentTypeId = this.entrustEquipmentTypeSelect.find(
        (i) => i.name == "个人剂量"
      )?.entrustEquipmentTypeId;
      this.$set(
        this.form.tasksContractItemList[maxIndex - 1],
        "entrustEquipmentTypeId",
        entrustEquipmentTypeId
      );
      this.changeEquipmentType(entrustEquipmentTypeId, maxIndex - 1);
      this.$set(this.form.tasksContractItemList[maxIndex - 1], "CG", ["1"]);
    },
    // 校验台件数并计算总价
    changeNum(val, index) {
      let reg = /^[1-9]\d*$/;
      if (val && !reg.test(val)) {
        this.$modal.msgWarning("请输入正确的台件数");
        this.form.tasksContractItemList[index].num = null;
        // 更新总价
        this.form.tasksContractItemList[index].total = null;
        this.calculateTotalprice();
        return;
      }
      // 更新总价
      if (
        this.form.tasksContractItemList[index].num &&
        this.form.tasksContractItemList[index].amount
      ) {
        this.form.tasksContractItemList[index].total =
          this.form.tasksContractItemList[index].num *
          this.form.tasksContractItemList[index].amount;
      } else {
        this.form.tasksContractItemList[index].total = null;
      }
      this.calculateTotalprice();
    },
    // 校验单价并计算总价
    changeAmount(val, index) {
      let reg = /^[0-9]+([.]{1}[0-9]{1,3})?$/;
      if (val && !reg.test(val)) {
        this.$modal.msgWarning("请输入正确的金额");
        this.form.tasksContractItemList[index].amount = null;
        // 更新总价
        this.form.tasksContractItemList[index].total = null;
        this.calculateTotalprice();
        return;
      }
      // 更新总价
      if (
        this.form.tasksContractItemList[index].num &&
        this.form.tasksContractItemList[index].amount
      ) {
        this.form.tasksContractItemList[index].total =
          this.form.tasksContractItemList[index].num *
          this.form.tasksContractItemList[index].amount;
      } else {
        this.form.tasksContractItemList[index].total = null;
      }
      this.calculateTotalprice();
    },
    // 合计
    calculateTotalprice() {
      this.totalprice = 0;
      this.form.tasksContractItemList.forEach((item) => {
        this.totalprice += item.total;
      });
    },
    // 单选框可取消
    handleChangeRadioInspecId(row, index, changeId) {
      let newRow = {
        ...row,
        radioInspecId: row.radioInspecId === changeId ? "" : changeId,
      };
      this.$set(this.form.tasksContractItemList, index, newRow);
    },
    // 点击合同评审表
    handleOpenContractReviewTable() {
      this.showContractReviewTableDialog = true;
    },
    // 处理合同评审表暂存
    handleContractReviewTableTempSave(data) {
      this.contractReviewTableIsTempSave = true;
      this.contractReviewTableData = data;
    },
    // 点击合同评审记录表
    handleOpenContractReviewRecordTable(row) {
      this.currRow = row;
      this.showContractReviewRecordTableDialog = true;
    },
    // 点击生成合同
    handleGenerateContract(row) {
      generateContract(row.tasksContractId)
        .then((res) => {
          this.$message.success("操作成功");
          // this.getList()
        })
        .catch((err) => {});
    },
    // 点击生成任务
    handleGenerateTask(row) {
      generateDetectionTogetherTask(row.tasksContractId)
        .then((res) => {
          this.$message.success("操作成功");
          // this.getList()
        })
        .catch((err) => {});
    },
    // 处理合同评审记录表暂存
    handleContractReviewRecordTableTempSave(data) {
      this.contractReviewRecordTableIsTempSave = true;
      this.contractReviewRecordTableData = data;
    },
    // 点击生成
    handleGenerateContractReviewTable(row) {
      this.currRow = row;

      if (!this.currRow?.tasksContractId) {
        this.$message.error("请先添加合同任务");
        return;
      }
      this.generateBtnLoading = true;
      const tasksContractId = this.currRow.tasksContractId;
      generateContractReviewContent(tasksContractId)
        .then((res) => {
          this.generateBtnLoading = false;
          this.$message.success("生成成功");
          this.reviewOssId = res.data || "";
          this.getList();
        })
        .catch((err) => {
          this.generateBtnLoading = false;
        });
    },
    // 点击打印
    handlePrintContractReviewTable(row) {
      listByIds(row.reviewOssId)
        .then((res) => {
          const fileUrl = res.data[0].url;
          window.open(fileUrl, "PDF", "");
        })
        .catch((err) => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

.operation {
  margin-bottom: 15px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
.el-table .warning-row {
  background: rgb(228, 13, 13);
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.innertitle {
  margin-bottom: 10px;
  position: relative;
  color: #252d57;
  font-weight: bold;
  padding-left: 15px;
  font-size: 18px;
  line-height: 20px;
  &::before {
    content: "";
    width: 5px;
    height: 100%;
    background-color: #2a72ee;
    border-radius: 5px;
    position: absolute;
    left: 0;
    bottom: 0;
  }
  .addline {
    float: right;
    padding-inline: 25px;
    transform: translateY(-7px);
  }
}
.inspect {
  display: flex;
  align-items: center;
  justify-content: center;
  .inspectcheckbox {
    margin-right: 20px;
    display: flex;
    align-items: center;
  }
  .inspectradio {
    .el-radio {
      margin-right: 13px;
    }
  }
}
.adddialog ::v-deep .el-dialog__body {
  height: 600px;
}
.tableoperation {
  margin-bottom: 0;
}
.adddialog ::v-deep .el-table__body .el-table__cell {
  padding-block: 4px;
}
</style>
